{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "dotnet_interactive": {
     "language": "csharp"
    },
    "polyglot_notebook": {
     "kernelName": "csharp"
    },
    "vscode": {
     "languageId": "polyglot-notebook"
    }
   },
   "outputs": [],
   "source": [
    "#load \"LoadBaseToolWPF.csx\"\n",
    "\n",
    "using BaseTool;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 接收数据缓冲区\n",
    "\n",
    "下面的代码需要配合【网络调试助手】使用。\n",
    "\n",
    "在 10 秒内通过网络调试助手发送任何数据，即使没有执行 Receive 函数，后续再执行 Receive 也行。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "dotnet_interactive": {
     "language": "csharp"
    },
    "polyglot_notebook": {
     "kernelName": "csharp"
    },
    "vscode": {
     "languageId": "polyglot-notebook"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Socket数据接收缓冲区大小：65536\n",
      "|  DEC |  HEX |       Bin |\n",
      "| ---- | ---- | --------- |\n",
      "|    1 |   01 | 0000-0001 |\n",
      "|    3 |   03 | 0000-0011 |\n",
      "\n"
     ]
    }
   ],
   "source": [
    "using System.Net;\n",
    "using System.Net.Sockets;\n",
    "\n",
    "Socket _socket  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n",
    "_socket.Connect(IPAddress.Parse(\"127.0.0.1\"), 5000);\n",
    "$\"Socket数据接收缓冲区大小：{_socket.ReceiveBufferSize}\".Dump();\n",
    "\n",
    "Task.Delay(10000).Wait();\n",
    "\n",
    "byte[] _byte_array = new byte[2];\n",
    "int _length = _socket.Receive(_byte_array);\n",
    "BaseTransform.FormatShowArray(_byte_array[0.._length]).Dump();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在没有连接的时候关闭 Socket\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "dotnet_interactive": {
     "language": "csharp"
    },
    "polyglot_notebook": {
     "kernelName": "csharp"
    },
    "vscode": {
     "languageId": "polyglot-notebook"
    }
   },
   "outputs": [],
   "source": [
    "try\n",
    "{\n",
    "    Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n",
    "    _socket.Bind(new IPEndPoint(IPAddress.Any, 5001));\n",
    "    _socket.Listen();\n",
    "    _socket.AcceptAsync();\n",
    "\n",
    "    Task.Delay(2000).Wait();\n",
    "\n",
    "    if(_socket.Connected)\n",
    "    {\n",
    "        _socket.Shutdown(SocketShutdown.Both);\n",
    "    }\n",
    "    _socket.Close();\n",
    "}\n",
    "catch(Exception ex)\n",
    "{\n",
    "    Console.WriteLine($\"{ex}\");\n",
    "}\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "csharp"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
